package es.buffygilmore.dietadisociada.modelo.db;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import es.buffygilmore.dietadisociada.modelo.db.DietaDisociadaContract.Grupo;

public class DietaDisociadaProvider extends ContentProvider {

	private DietaDisociadaDbHelper dietaDisociadaDbHelper;

	private static final UriMatcher sUriMatcher;

	static {
		sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		sUriMatcher.addURI(DietaDisociadaContract.AUTHORITY, "grupo",
				DietaDisociadaContract.GRUPOS);
		sUriMatcher.addURI(DietaDisociadaContract.AUTHORITY, "grupo/#",
				DietaDisociadaContract.GRUPO_ID);
	}

	@Override
	public boolean onCreate() {
		dietaDisociadaDbHelper = new DietaDisociadaDbHelper(getContext());
		return true;
	}

	@Override
	public Cursor query(final Uri uri, final String[] projection,
			final String selection, final String[] selectionArgs,
			final String sortOrder) {
		final SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
		sqlBuilder.setTables(Grupo.TABLE_NAME);
		if (sUriMatcher.match(uri) == DietaDisociadaContract.GRUPO_ID) {
			sqlBuilder.appendWhere("id" + " = " + uri.getPathSegments().get(1));
		}
		final SQLiteDatabase db = dietaDisociadaDbHelper.getReadableDatabase();
		final Cursor c = sqlBuilder.query(db, projection, selection,
				selectionArgs, null, null, sortOrder);
		// ---register to watch a content URI for changes---
		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;
	}

	@Override
	public String getType(final Uri paramUri) {
		switch (sUriMatcher.match(paramUri)) {
		case DietaDisociadaContract.GRUPOS:
			return Grupo.CONTENT_TYPE;
		case DietaDisociadaContract.GRUPO_ID:
			return Grupo.CONTENT_ITEM_TYPE;
		default:
			throw new IllegalArgumentException("Unknown URI " + paramUri);
		}
	}

	@Override
	public Uri insert(final Uri paramUri, final ContentValues paramContentValues) {
		throw new UnsupportedOperationException();
	}

	@Override
	public int delete(final Uri paramUri, final String paramString,
			final String[] paramArrayOfString) {
		throw new UnsupportedOperationException();
	}

	@Override
	public int update(final Uri paramUri,
			final ContentValues paramContentValues, final String paramString,
			final String[] paramArrayOfString) {
		throw new UnsupportedOperationException();
	}

}
